#!/usr/bin/python
# -*- coding: UTF-8 -*-
from tkinter import *
import tkinter.filedialog
from tkinter import ttk
from tkinter import messagebox
from serial import *

class Window:
    def init_frames(self):
        self.cb_frame = Frame(self.root, bg="white")
        self.cb_frame.place(x=20, y = 20)
        self.btn_frame = Frame(self.root, bg="white")
        self.btn_frame.place(x=20, y = 500)

    def init_comx_disp(self):
        self.comx_label = Label(self.cb_frame,text='串口号', bg="white")#绝对坐标1，1

        self.name = StringVar()
        self.comx_cb = ttk.Combobox(self.cb_frame, textvariable=self.name)
        self.comx_cb["state"] = "readonly"
        self.comx_cb.set("选择串口号")
        self.comx_label.grid(row=0, column=0)
        self.comx_cb.grid(row=0, column=1)

    def init_baud_disp(self):
        self.baud_label = Label(self.cb_frame,text='波特率', bg="white")#绝对坐标1，1

        self.name = StringVar()
        self.baud_cb = ttk.Combobox(self.cb_frame, textvariable=self.name)
        self.baud_cb["values"] = ("4800", "9600", "115200")
        self.baud_cb["state"] = "readonly"

        # self.baud_cb.set(9600)
        self.baud_cb.current(1)
        self.baud_label.grid(row=0, column=2)
        self.baud_cb.grid(row=0, column=3)

    def init_paritybit_disp(self):
        self.paritybit_label = Label(self.cb_frame,text='校验位', bg="white").grid(row=1, column=0)#绝对坐标1，1

        self.name = StringVar()
        self.paritybit_cb = ttk.Combobox(self.cb_frame, textvariable=self.name)
        self.paritybit_cb["value"] = ["NONE", "EVEN", "ODD", "MARK", "SPACE"]
        self.paritybit_cb["state"] = "readonly"
        self.paritybit_cb.grid(row=1, column=1)

    def init_databit_disp(self):
        self.databit_label = Label(self.cb_frame,text='数据位', bg="white").grid(row=1, column=2)#绝对坐标1，1

        self.name = StringVar()
        self.databit_cb = ttk.Combobox(self.cb_frame, textvariable=self.name)
        self.databit_cb["value"] = [5, 6, 7, 8]
        self.databit_cb["state"] = "readonly"
        self.databit_cb.set(8)
        self.databit_cb.grid(row=1, column=3)

    def init_btn_connect(self):
        def stop_connect():
            self.ser.close()
        def btn_switch():
            if self.btn_connect['text'] == "打开串口":
                chosen_port = self.get_comx_cb()
                if chosen_port[4] == ' ':
                    chosen_port = chosen_port[0:4]
                else:
                    chosen_port = chosen_port[0:5]
                # print(chosen_port[0:3])
                if chosen_port[0:3] != "COM":
                    messagebox.showinfo( "错误", "请选择端口")
                    return
                else:
                    self.connect_sign = True
            elif self.btn_connect['text'] == "关闭串口":
                print("hhh")
                self.connect_sign = False
                self.btn_connect['text'] = "打开串口"
                stop_connect()
            return
        self.btn_connect = Button(self.cb_frame, text ="打开串口", command = btn_switch)
        self.btn_connect.grid(row=2, column=0)

    def init_btn_send(self):
        
        def convert(act):
            s = ''
            if act[0] == "正":
                s = s+'C'
            elif act[0] == "反":
                s = s+'I'
            else:
                s = s+'T'
            s=s+' '
            if act[1] == "快":
                s = s+'H'
            elif act[1] == "中":
                s = s+'M'
            elif act[1] == "慢":
                s = s+'L'
            s=s+' '
            
            time_s = act[2:]
            s = s+time_s
            
            b = bytes([0x80])+str.encode(s)+bytes([0xff])
            return b

        def start_send():

            if self.ser.isOpen() == True:
                dir_s = ["正", "反", "停"]
                spd_s = ["快", "中", "慢"]
                add0 = ""
                if len(self.ety_second.get()) <= 1:
                    add0 = "0"
                time_s = "0:00:0"
                
                act = dir_s[self.dir_v.get()] + spd_s[self.spd_v.get()] + time_s
                b = convert(act)
                self.ser.write(b)
                
        self.btn_send = Button(self.btn_frame, text ="发送", command = start_send)
        self.btn_send.grid(row=0, column=0)

    def init_proc_lb(self):
        self.listb = Listbox(self.root)
        self.listb.place(x=20,y=120, width = 440)
        
    def init_dir_rb(self):
        self.dir_v = IntVar()
        print(self.dir_v.get())

        self.state_frame = Frame(self.root, bg="white")
        # frame.place(relx=0.3, rely=0.3, relwidth=0.4, relheight=0.4)
        self.state_frame.place(x=30, y = 320)

        # 单选框
        r1 = Radiobutton(self.state_frame, text="正转", value=0, variable=self.dir_v, bg="white")
        r1.grid(row=0, column=0)

        r2 = Radiobutton(self.state_frame, text="反转", value=1, variable=self.dir_v, bg="white")
        r2.grid(row=1, column=0)
        
        r2 = Radiobutton(self.state_frame, text="停", value=2, variable=self.dir_v, bg="white")
        r2.grid(row=2, column=0)
        
        self.spd_v = IntVar()
        # 单选框
        r1 = Radiobutton(self.state_frame, text="快", value=0, variable=self.spd_v, bg="white")
        r1.grid(row=0, column=1)
        r2 = Radiobutton(self.state_frame, text="中", value=1, variable=self.spd_v, bg="white")
        r2.grid(row=1, column=1)
        r2 = Radiobutton(self.state_frame, text="慢", value=2, variable=self.spd_v, bg="white")
        r2.grid(row=2, column=1)
 
    def init_time_Entry(self):
        zero = StringVar(value='0')
        self.ety_minute = Entry(self.root, bd =1, width = 3, textvariable=zero)
        self.ety_minute.place(x=250,y=400)
        zero1 = StringVar(value='0')
        self.ety_second = Entry(self.root, bd =1, width = 3, textvariable=zero1)
        self.ety_second.place(x=300,y=400)
        zero2 = StringVar(value='0')
        self.ety_millis = Entry(self.root, bd =1, width = 3, textvariable=zero2)
        self.ety_millis.place(x=350,y=400)


    def init_btn_add_auto(self):
        def add_auto():
            dir_s = ["正", "反", "停"]
            spd_s = ["快", "中", "慢"]
            add0 = ""
            if len(self.ety_second.get()) <= 1:
                add0 = "0"
            
            time_s = self.ety_minute.get() + ":" + add0 + self.ety_second.get() + ":" + self.ety_millis.get()
            self.listb.insert("end", dir_s[self.dir_v.get()] + spd_s[self.spd_v.get()] + time_s)
        self.btn_auto = Button(self.btn_frame, text = "添加顺序动作", command = add_auto)
        self.btn_auto.grid(row=0, column=1)
 
    def init_btn_auto(self):
        def start_auto():
            print(self.btn_auto["text"])
            if self.btn_auto["text"] == "开始顺序动作":
                self.auto_state = True
                self.btn_auto["text"] = "停止顺序动作"
            elif self.btn_auto["text"] == "停止顺序动作":
                self.auto_state = False
                self.btn_auto["text"] = "开始顺序动作"
        self.btn_auto = Button(self.btn_frame, text ="开始顺序动作", command = start_auto)
        self.btn_auto.grid(row=0, column=2)

    def init_btn_save(self):
        def save():
            filename = tkinter.filedialog.asksaveasfilename(title='保存文件', defaultextension="*.txt",filetypes=[("text", ".txt")])
            with open(filename, 'w') as f:
                list_log = self.listb.get(0, "end")
                for fp in list_log:
                    f.write(str(fp))
                    f.write('\n')
        self.btn_save = Button(self.btn_frame, text ="保存动作序列", command = save)
        self.btn_save.grid(row=0, column=3)
 
    def init_btn_open(self):
        def open_file():
            filename = tkinter.filedialog.askopenfilename()
            with open(filename, 'r') as f:
                list_read = f.readlines()
                for li in list_read:
                    self.listb.insert("end", li.replace("\n", ""))
        self.btn_open = Button(self.btn_frame, text ="打开动作序列", command = open_file)
        self.btn_open.grid(row=0, column=4)
 
    def init_btn_flush(self):
        def flush_list():
            self.listb.delete(0, END)

        self.btn_flush = Button(self.btn_frame, text ="清空动作序列", command = flush_list)
        self.btn_flush.grid(row=0, column=5)
 

    def init_window(self):
        self.root=Tk()
        # self.root.protocol("WM_DELETE_WINDOW", self.onClose)
        self.root.title('上位机')
        mycolor = '#%02x%02x%02x' % (255, 255, 255)  # set your favourite rgb color
        self.root.configure(bg=mycolor)
        self.root['width']=500
        self.root['height']=600  #初始化窗口大小
        self.init_frames()
        self.init_comx_disp()
        self.init_btn_connect()
        self.init_baud_disp()
        self.init_btn_send()
        self.init_proc_lb()
        self.init_dir_rb()
        self.init_time_Entry()
        self.init_paritybit_disp()
        self.init_databit_disp()
        self.init_btn_add_auto()
        self.init_btn_auto()
        self.init_btn_save()
        self.init_btn_open()
        self.init_btn_flush()
        self.baud_cb.set(9600)
        self.paritybit_cb.set("NONE")

    def __init__(self):
        super().__init__()
        self.init_window()
        self.on = True
        self.auto_state = False
        self.connect_sign = False
    
    def start(self):
        self.root.mainloop()
    
    def set_comx_cb(self, values):
        if len(values) == 0:
            self.comx_cb.set("重新选择串口号")
        else:
            self.comx_cb.set(values[0])
        self.comx_cb["values"] = (values)
    
    def get_auto_state(self):
        return self.auto_state

    def get_comx_cb(self):
        return self.comx_cb.get()

    def get_baud_cb(self):
        return int(self.baud_cb.get())
        
